<!Doctype html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title>Java 多线程编程 | 菜鸟教程</title>

  <meta name='robots' content='max-image-preview:large' />
<link rel='stylesheet' id='classic-theme-styles-css' href='../0/classic-themes.min.css?ver=6.2' type='text/css' media='all' />
<link rel="canonical" href="../java/java-multithreading.html" />
<meta name="keywords" content="Java 多线程编程">
<meta name="description" content="Java 多线程编程   Java 给多线程编程提供了内置的支持。 一条线程指的是进程中一个单一顺序的控制流，一个进程中可以并发多个线程，每条线程并行执行不同的任务。 多线程是多任务的一种特别的形式，但多线程使用了更小的资源开销。 这里定义和线程相关的另一个术语 - 进程：一个进程包括由操作系统分配的内存空间，包含一个或多个线程。一个线程不能独立的存在，它必须是进程的一部分。一个进程一直运行，直到所有的非守护线程都结束运行后才能结束。 ..">
		
	<link rel="shortcut icon" href="https://static.runoob.com/images/favicon.ico">
	<link rel="stylesheet" href="../0/style.css?v=1.170" type="text/css" media="all" />	
	<link rel="stylesheet" href="../0/font-awesome.min.css" media="all" />	
  <!--[if gte IE 9]><!-->
  <script src=""></script>
  <!--<![endif]-->
  <!--[if lt IE 9]>
     <script src=""></script>
     <script src=""></script>
  <![endif]-->
  <link rel="apple-touch-icon" href="https://static.runoob.com/images/icon/mobile-icon.png"/>
  <meta name="apple-mobile-web-app-title" content="菜鸟教程">
</head>
<body>

<!--  头部 -->
<div class="container logo-search">

  <div class="col search row-search-mobile">
    <form action="index.php">
      <input class="placeholder" placeholder="搜索……" name="s" autocomplete="off">
      
    </form>
  </div>

  <div class="row">
    <div class="col logo">
      <h1><a href="../">菜鸟教程 -- 学的不仅是技术，更是梦想！</a></h1>
    </div>
        <div class="col right-list"> 
    <button class="btn btn-responsive-nav btn-inverse" data-toggle="collapse" data-target=".nav-main-collapse" id="pull" style=""> <i class="fa fa-navicon"></i> </button>
    </div>
        
    <div class="col search search-desktop last">
      <div class="search-input" >
      <form action="//www.runoob.com/" target="_blank">
        <input class="placeholder" id="s" name="s" placeholder="搜索……"  autocomplete="off" style="height: 44px;">
      </form>
      
      </div>
    </div>
  </div>
</div>



<!-- 导航栏 -->
<!-- 导航栏 -->
<div class="container navigation">
	<div class="row">
		<div class="col nav">
			<ul class="pc-nav" id="runoob-detail-nav">
				<li><a href="../">首页</a></li>
				<li><a href="../html/html-tutorial.html">HTML</a></li>
				<li><a href="../css/css-tutorial.html">CSS</a></li>
				<li><a href="../js/js-tutorial.html">JavaScript</a></li>
				<li><a href="javascript:void(0);" data-id="vue">Vue</a></li>
				<li><a href="javascript:void(0);" data-id="bootstrap">Bootstrap</a></li>
				<li><a href="../nodejs/nodejs-tutorial.html">NodeJS</a></li>
				<li><a href="../python3/python3-tutorial.html">Python3</a></li>
				<li><a href="../python/python-tutorial.html">Python2</a></li>
				<li><a href="../java/java-tutorial.html">Java</a></li>
				<li><a href="../cprogramming/c-tutorial.html">C</a></li>
				<li><a href="../cplusplus/cpp-tutorial.html">C++</a></li>
				<li><a href="../csharp/csharp-tutorial.html">C#</a></li>
				<li><a href="../go/go-tutorial.html">Go</a></li>
				<li><a href="../sql/sql-tutorial.html">SQL</a></li>
				<li><a href="../linux/linux-tutorial.html">Linux</a></li>
				<li><a href="../jquery/jquery-tutorial.html">jQuery</a></li>
				<li><a href="../browser-history">本地书签</a></li>
				<!--
			
				<li><a href="../w3cnote/knowledge-start.html" style="font-weight: bold;" onclick="_hmt.push(['_trackEvent', '星球', 'click', 'start'])" title="我的圈子">我的圈子</a></li>				
				<li><a href="javascript:;" class="runoob-pop">登录</a></li>
				-->
      		</ul>
			<ul class="mobile-nav">
				<li><a href="../">首页</a></li>
				<li><a href="../html/html-tutorial.html">HTML</a></li>
				<li><a href="../css/css-tutorial.html">CSS</a></li>
				<li><a href="../js/js-tutorial.html">JS</a></li>
				<li><a href="../browser-history">本地书签</a></li>
				<li><a href="javascript:void(0)" class="search-reveal">Search</a> </li>
			</ul>
			
		</div>
	</div>
</div>

<div class="container sub-navigation sub-navigation-articles" style="display:none">
	<div class="row">
		<div class="col nav-sub">
		<ul id="python">
			<li class="cat-item"><a href="../python3/python3-tutorial.html">Python3 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../python/python-tutorial.html">Python2 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
		</ul>
		<ul id="vue">
			<li class="cat-item"><a href="../vue3/vue3-tutorial.html">Vue3 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../vue/vue-tutorial.html">vue2 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
		</ul>

		<ul id="bootstrap">
			<li class="cat-item"><a href="../bootstrap/bootstrap-tutorial.html">Bootstrap3 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../bootstrap4/bootstrap4-tutorial.html">Bootstrap4 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../bootstrap5/bootstrap5-tutorial.html">Bootstrap5 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../bootstrap/bootstrap-v2-tutorial.html">Bootstrap2 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
		</ul>
		</div>
	</div>
</div><!--  内容  -->
<div class="container main">
	<!-- 中间 -->
	<div class="row">
	
<div class="runoob-col-md2">
<div class="left-column">
	<div class="tab" style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
	<i class="fa fa-list" aria-hidden="true"></i> 
	<span>Java 教程</span>
	<a data-cate="53" href="javascript:void(0);" title="夜间模式"  id="moon"><i class="fa fa-moon-o" aria-hidden="true" style="line-height: 28px;font-size: 1.2em;margin: 2px 4px 0;"></i></a>
	<a data-cate="53" style="display:none;" href="javascript:void(0);" title="日间模式"  id="sun" ><i class="fa fa-sun-o" aria-hidden="true" style="line-height: 28px;font-size: 1.2em;margin: 2px 4px 0;line-height: 28px;
}"></i></a>

	</div>
	<div class="sidebar-box gallery-list">
		<div class="design" id="leftcolumn">
						<a target="_top" title="Java 教程"  href="../java/java-tutorial.html" >
			Java 教程			</a>
						<a target="_top" title="Java 简介"  href="../java/java-intro.html" >
			Java 简介			</a>
						<a target="_top" title="Java 开发环境配置"  href="../java/java-environment-setup.html" >
			Java 开发环境配置			</a>
						<a target="_top" title="Java 基础语法"  href="../java/java-basic-syntax.html" >
			Java 基础语法			</a>
						<a target="_top" title="Java 对象和类"  href="../java/java-object-classes.html" >
			Java 对象和类			</a>
						<a target="_top" title="Java 基本数据类型"  href="../java/java-basic-datatypes.html" >
			Java 基本数据类型			</a>
						<a target="_top" title="Java 变量类型"  href="../java/java-variable-types.html" >
			Java 变量类型			</a>
						<a target="_top" title="Java 修饰符"  href="../java/java-modifier-types.html" >
			Java 修饰符			</a>
						<a target="_top" title="Java 运算符"  href="../java/java-operators.html" >
			Java 运算符			</a>
						<a target="_top" title="Java 循环结构 &#8211; for, while 及 do&#8230;while"  href="../java/java-loop.html" >
			Java 循环结构			</a>
						<a target="_top" title="Java 条件语句 &#8211; if&#8230;else"  href="../java/java-if-else-switch.html" >
			Java 条件语句			</a>
			<a target="_top" title="Java switch case 语句" href="../java/java-switch-case.html">Java switch case</a>			<a target="_top" title="Java Number &#038; Math 类"  href="../java/java-number.html" >
			Java Number & Math 类			</a>
						<a target="_top" title="Java Character 类"  href="../java/java-character.html" >
			Java Character 类			</a>
						<a target="_top" title="Java String 类"  href="../java/java-string.html" >
			Java String 类			</a>
						<a target="_top" title="Java StringBuffer 和 StringBuilder 类"  href="../java/java-stringbuffer.html" >
			Java StringBuffer			</a>
						<a target="_top" title="Java 数组"  href="../java/java-array.html" >
			Java 数组			</a>
						<a target="_top" title="Java 日期时间"  href="../java/java-date-time.html" >
			Java 日期时间			</a>
						<a target="_top" title="Java 正则表达式"  href="../java/java-regular-expressions.html" >
			Java 正则表达式			</a>
						<a target="_top" title="Java 方法"  href="../java/java-methods.html" >
			Java 方法			</a>
						<a target="_top" title="Java 流(Stream)、文件(File)和IO"  href="../java/java-files-io.html" >
			Java Stream、File、IO			</a>
			<a target="_top" title="Java Scanner 类" href="java-scanner-class.html"> Java Scanner 类 </a>			<a target="_top" title="Java 异常处理"  href="../java/java-exceptions.html" >
			Java 异常处理			</a>
			<br><h2 class="left">Java <span class="left_h2">面向对象</span></h2>			<a target="_top" title="Java 继承"  href="../java/java-inheritance.html" >
			Java 继承			</a>
						<a target="_top" title="Java 重写(Override)与重载(Overload)"  href="../java/java-override-overload.html" >
			Java Override/Overload			</a>
						<a target="_top" title="Java 多态"  href="../java/java-polymorphism.html" >
			Java 多态			</a>
						<a target="_top" title="Java 抽象类"  href="../java/java-abstraction.html" >
			Java 抽象类			</a>
						<a target="_top" title="Java 封装"  href="../java/java-encapsulation.html" >
			Java 封装			</a>
						<a target="_top" title="Java 接口"  href="../java/java-interfaces.html" >
			Java 接口			</a>
			<a target="_top" title="Java 枚举" href="../java/java-enum.html">
			Java 枚举			</a>			<a target="_top" title="Java 包(package)"  href="../java/java-package.html" >
			Java 包(package)			</a>
			<br><h2 class="left">Java <span class="left_h2">高级教程</span></h2>			<a target="_top" title="Java 数据结构"  href="../java/java-data-structures.html" >
			Java 数据结构			</a>
						<a target="_top" title="Java 集合框架"  href="../java/java-collections.html" >
			Java 集合框架			</a>
			<a target="_top" title="Java ArrayList" href="../java/java-arraylist.html">Java ArrayList</a>
<a target="_top" title="Java LinkedList" href="../java/java-linkedlist.html">Java LinkedList</a>
<a target="_top" title="Java HashSet" href="../java/java-hashset.html">Java HashSet</a>
<a target="_top" title="Java  HashMap" href="../java/java-hashmap.html">Java  HashMap</a>
<a target="_top" title="Java  Iterator" href="../java/java-iterator.html">Java  Iterator</a>
<a target="_top" title="Java  Object" href="../java/java-object-class.html">Java  Object</a>			<a target="_top" title="Java 泛型"  href="../java/java-generics.html" >
			Java 泛型			</a>
						<a target="_top" title="Java 序列化"  href="../java/java-serialization.html" >
			Java 序列化			</a>
						<a target="_top" title="Java 网络编程"  href="../java/java-networking.html" >
			Java 网络编程			</a>
						<a target="_top" title="Java 发送邮件"  href="../java/java-sending-email.html" >
			Java 发送邮件			</a>
						<a target="_top" title="Java 多线程编程"  href="../java/java-multithreading.html" >
			Java 多线程编程			</a>
						<a target="_top" title="Java Applet 基础"  href="../java/java-applet-basics.html" >
			Java Applet 基础			</a>
						<a target="_top" title="Java 文档注释"  href="../java/java-documentation.html" >
			Java 文档注释			</a>
						<a target="_top" title="Java 实例"  href="../java/java-examples.html" >
			Java 实例			</a>
						<a target="_top" title="Java 8  新特性"  href="../java/java8-new-features.html" >
			Java 8  新特性			</a>
						<a target="_top" title="Java MySQL 连接"  href="../java/java-mysql-connect.html" >
			Java MySQL 连接			</a>
						<a target="_top" title="Java 9 新特性"  href="../java/java9-new-features.html" >
			Java 9 新特性			</a>
			<a target="_blank" title="Java 测验" href="../quiz/java-quiz.html">Java 测验</a>	
		</div>
	</div>	
</div>
</div>	<div class="col middle-column">
		
	
	<div class="article">
		
		<div class="previous-next-links">
			<div class="previous-design-link"><i style="font-size:16px;" class="fa fa-arrow-left" aria-hidden="true"></i> <a href="../java/java-sending-email.html" rel="prev"> Java 发送邮件</a> </div>
			<div class="next-design-link"><a href="../java/java-applet-basics.html" rel="next"> Java Applet 基础</a> <i style="font-size:16px;" class="fa fa-arrow-right" aria-hidden="true"></i></div>
		</div>
<div class="article-heading-ad" style="display: block;">
<script async src=""
     crossorigin="anonymous"></script>
<!-- 728*90 固定 -->
<ins class="adsbygoogle"
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-5751451760833794"
     data-ad-slot="2147566827"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
		</div>
		<div class="article-body">
		
			<div class="article-intro" id="content">
			
			<h1>Java 多线程编程
</h1>
<p>
Java 给多线程编程提供了内置的支持。
一条线程指的是进程中一个单一顺序的控制流，一个进程中可以并发多个线程，每条线程并行执行不同的任务。</p><p>
多线程是多任务的一种特别的形式，但多线程使用了更小的资源开销。</p><p>
这里定义和线程相关的另一个术语 - 进程：一个进程包括由操作系统分配的内存空间，包含一个或多个线程。一个线程不能独立的存在，它必须是进程的一部分。一个进程一直运行，直到所有的非守护线程都结束运行后才能结束。</p><p>
多线程能满足程序员编写高效率的程序来达到充分利用 CPU 的目的。</p><hr>
<h2>
一个线程的生命周期
</h2>
<p>
线程是一个动态执行的过程，它也有一个从产生到死亡的过程。</p><p>下图显示了一个线程完整的生命周期。</p>
<p>
<img decoding="async" src="//www.runoob.com/wp-content/uploads/2014/01/java-thread.jpg"/>
</p>
<ul>
<li><b>新建状态:</b><p>使用 <strong>new</strong> 关键字和 <strong>Thread</strong> 类或其子类建立一个线程对象后，该线程对象就处于新建状态。它保持这个状态直到程序 <strong>start()</strong> 这个线程。</p></li>

<li><b>就绪状态:</b><p>当线程对象调用了start()方法之后，该线程就进入就绪状态。就绪状态的线程处于就绪队列中，要等待JVM里线程调度器的调度。</p></li>
<li><b>运行状态:</b><p>如果就绪状态的线程获取 CPU 资源，就可以执行 <strong>run()</strong>，此时线程便处于运行状态。处于运行状态的线程最为复杂，它可以变为阻塞状态、就绪状态和死亡状态。</p></li>
<li><b>阻塞状态:</b><p>如果一个线程执行了sleep（睡眠）、suspend（挂起）等方法，失去所占用资源之后，该线程就从运行状态进入阻塞状态。在睡眠时间已到或获得设备资源后可以重新进入就绪状态。可以分为三种：  </p>

<ul><li><p>等待阻塞：运行状态中的线程执行 wait() 方法，使线程进入到等待阻塞状态。
</p></li><li><p>同步阻塞：线程在获取 synchronized 同步锁失败(因为同步锁被其他线程占用)。
</p></li><li><p>其他阻塞：通过调用线程的 sleep() 或 join() 发出了 I/O 请求时，线程就会进入到阻塞状态。当sleep() 状态超时，join() 等待线程终止或超时，或者 I/O 处理完毕，线程重新转入就绪状态。</p></li>

</ul>
</li>
<li><b>死亡状态: </b><p>一个运行状态的线程完成任务或者其他终止条件发生时，该线程就切换到终止状态。</p></li>
</ul>
<hr>
<h2>
线程的优先级</h2>
<p>每一个 Java 线程都有一个优先级，这样有助于操作系统确定线程的调度顺序。</p><p>Java 线程的优先级是一个整数，其取值范围是 1 （Thread.MIN_PRIORITY ） - 10 （Thread.MAX_PRIORITY ）。</p><p>默认情况下，每一个线程都会分配一个优先级 NORM_PRIORITY（5）。
</p><p>具有较高优先级的线程对程序更重要，并且应该在低优先级的线程之前分配处理器资源。但是，线程优先级不能保证线程执行的顺序，而且非常依赖于平台。</p>
<hr>
<h2>
创建一个线程</h2>
<p>Java 提供了三种创建线程的方法：</p>
<ul><li>
通过实现 Runnable 接口；</li><li>
通过继承  Thread 类本身；</li>
<li>通过 Callable 和 Future 创建线程。</li>
</ul>
<hr><h2>
通过实现 Runnable 接口来创建线程</h2>
<p>
创建一个线程，最简单的方法是创建一个实现 Runnable 接口的类。</p><p>
为了实现 Runnable，一个类只需要执行一个方法调用 run()，声明如下：</p><p>
<div class="example">
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">run</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span></div>
</div>
</div>
<p>
你可以重写该方法，重要的是理解的 run() 可以调用其他方法，使用其他类，并声明变量，就像主线程一样。</p><p>
在创建一个实现 Runnable 接口的类之后，你可以在类中实例化一个线程对象。</p><p>
Thread 定义了几个构造方法，下面的这个是我们经常使用的：</p>
<div class="example">
<div class="example_code">
<div class="hl-main"><span class="hl-identifier">Thread</span><span class="hl-brackets">(</span><span class="hl-identifier">Runnable</span><span class="hl-code"> </span><span class="hl-identifier">threadOb</span><span class="hl-code">,</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">threadName</span><span class="hl-brackets">)</span><span class="hl-code">;</span></div>
</div>
</div>
<p>
这里，threadOb 是一个实现 Runnable 接口的类的实例，并且 threadName 指定新线程的名字。</p><p>
新线程创建之后，你调用它的 start() 方法它才会运行。</p>
<div class="example">
<div class="example_code">
<div class="hl-main"><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;</span></div>
</div>
</div>

<p>
下面是一个创建线程并开始让它执行的实例：
</p>
<div class="example"> 
<h2 class="example">实例</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">RunnableDemo</span><span class="hl-code"> </span><span class="hl-reserved">implements</span><span class="hl-code"> </span><span class="hl-identifier">Runnable</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
   </span><span class="hl-reserved">private</span><span class="hl-code"> </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-identifier">t</span><span class="hl-code">;
   </span><span class="hl-reserved">private</span><span class="hl-code"> </span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">threadName</span><span class="hl-code">;
   
   </span><span class="hl-identifier">RunnableDemo</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">threadName</span><span class="hl-code"> = </span><span class="hl-identifier">name</span><span class="hl-code">;
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Creating </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">run</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Running </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-reserved">try</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-reserved">for</span><span class="hl-brackets">(</span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">i</span><span class="hl-code"> = </span><span class="hl-number">4</span><span class="hl-code">; </span><span class="hl-identifier">i</span><span class="hl-code"> &gt; </span><span class="hl-number">0</span><span class="hl-code">; </span><span class="hl-identifier">i</span><span class="hl-code">--</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
            </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread: </span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">threadName</span><span class="hl-code"> + </span><span class="hl-quotes">&quot;</span><span class="hl-string">, </span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">i</span><span class="hl-brackets">)</span><span class="hl-code">;
            </span><span class="hl-comment">//</span><span class="hl-comment"> 让线程睡眠一会</span><span class="hl-comment"></span><span class="hl-code">
            </span><span class="hl-identifier">Thread</span><span class="hl-code">.</span><span class="hl-identifier">sleep</span><span class="hl-brackets">(</span><span class="hl-number">50</span><span class="hl-brackets">)</span><span class="hl-code">;
         </span><span class="hl-brackets">}</span><span class="hl-code">
      </span><span class="hl-brackets">}</span><span class="hl-reserved">catch</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">InterruptedException</span><span class="hl-code"> </span><span class="hl-identifier">e</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> + </span><span class="hl-quotes">&quot;</span><span class="hl-string"> interrupted.</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-brackets">}</span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> + </span><span class="hl-quotes">&quot;</span><span class="hl-string"> exiting.</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">start</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Starting </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-reserved">if</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">t</span><span class="hl-code"> == </span><span class="hl-reserved">null</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-identifier">t</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-reserved">this</span><span class="hl-code">, </span><span class="hl-identifier">threadName</span><span class="hl-brackets">)</span><span class="hl-code">;
         </span><span class="hl-identifier">t</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-brackets">}</span><span class="hl-code">
   </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span><span class="hl-code">
 
</span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">TestThread</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
 
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">static</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">main</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">args</span><span class="hl-brackets">[</span><span class="hl-brackets">]</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">RunnableDemo</span><span class="hl-code"> </span><span class="hl-identifier">R1</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">RunnableDemo</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread-1</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">R1</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
      
      </span><span class="hl-identifier">RunnableDemo</span><span class="hl-code"> </span><span class="hl-identifier">R2</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">RunnableDemo</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread-2</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">R2</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">   
</span><span class="hl-brackets">}</span></div>
</div><br>
</div>
<p>
编译以上程序运行结果如下：
 </p>
<pre>
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
</pre>
<hr>
<h2>
通过继承Thread来创建线程</h2>
<p>
创建一个线程的第二种方法是创建一个新的类，该类继承 Thread 类，然后创建一个该类的实例。</p><p>
继承类必须重写 run() 方法，该方法是新线程的入口点。它也必须调用 start() 方法才能执行。</p>
<p>该方法尽管被列为一种多线程实现方式，但是本质上也是实现了 Runnable 接口的一个实例。</p>
<div class="example"> 
<h2 class="example">实例</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">ThreadDemo</span><span class="hl-code"> </span><span class="hl-reserved">extends</span><span class="hl-code"> </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
   </span><span class="hl-reserved">private</span><span class="hl-code"> </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-identifier">t</span><span class="hl-code">;
   </span><span class="hl-reserved">private</span><span class="hl-code"> </span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">threadName</span><span class="hl-code">;
   
   </span><span class="hl-identifier">ThreadDemo</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">threadName</span><span class="hl-code"> = </span><span class="hl-identifier">name</span><span class="hl-code">;
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Creating </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">run</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Running </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-reserved">try</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-reserved">for</span><span class="hl-brackets">(</span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">i</span><span class="hl-code"> = </span><span class="hl-number">4</span><span class="hl-code">; </span><span class="hl-identifier">i</span><span class="hl-code"> &gt; </span><span class="hl-number">0</span><span class="hl-code">; </span><span class="hl-identifier">i</span><span class="hl-code">--</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
            </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread: </span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">threadName</span><span class="hl-code"> + </span><span class="hl-quotes">&quot;</span><span class="hl-string">, </span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">i</span><span class="hl-brackets">)</span><span class="hl-code">;
            </span><span class="hl-comment">//</span><span class="hl-comment"> 让线程睡眠一会</span><span class="hl-comment"></span><span class="hl-code">
            </span><span class="hl-identifier">Thread</span><span class="hl-code">.</span><span class="hl-identifier">sleep</span><span class="hl-brackets">(</span><span class="hl-number">50</span><span class="hl-brackets">)</span><span class="hl-code">;
         </span><span class="hl-brackets">}</span><span class="hl-code">
      </span><span class="hl-brackets">}</span><span class="hl-reserved">catch</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">InterruptedException</span><span class="hl-code"> </span><span class="hl-identifier">e</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> + </span><span class="hl-quotes">&quot;</span><span class="hl-string"> interrupted.</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-brackets">}</span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> + </span><span class="hl-quotes">&quot;</span><span class="hl-string"> exiting.</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">start</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Starting </span><span class="hl-quotes">&quot;</span><span class="hl-code"> +  </span><span class="hl-identifier">threadName</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-reserved">if</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">t</span><span class="hl-code"> == </span><span class="hl-reserved">null</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-identifier">t</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-reserved">this</span><span class="hl-code">, </span><span class="hl-identifier">threadName</span><span class="hl-brackets">)</span><span class="hl-code">;
         </span><span class="hl-identifier">t</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-brackets">}</span><span class="hl-code">
   </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span><span class="hl-code">
 
</span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">TestThread</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
 
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">static</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">main</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">args</span><span class="hl-brackets">[</span><span class="hl-brackets">]</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">ThreadDemo</span><span class="hl-code"> </span><span class="hl-identifier">T1</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">ThreadDemo</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread-1</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">T1</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
      
      </span><span class="hl-identifier">ThreadDemo</span><span class="hl-code"> </span><span class="hl-identifier">T2</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">ThreadDemo</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread-2</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">T2</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">   
</span><span class="hl-brackets">}</span></div>
</div><br>
</div>
<p>编译以上程序运行结果如下：
</p>
<pre>
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
</pre><hr>
<h2>
Thread 方法</h2>
<p>
下表列出了Thread类的一些重要方法：
</p>
<table class="reference">
	<tbody>
		<tr>
			<th>
				<strong>序号</strong></th>
			<th style="text-align: center;">
				<strong>方法描述</strong></th>
		</tr>
		<tr>
			<td>
				1</td>
			<td>
				<strong>public void start()</strong><br>
				使该线程开始执行；<b style="color:black;background-color:#ffff66">Java</b> 虚拟机调用该线程的&nbsp;run&nbsp;方法。</td>
		</tr>
		<tr>
			<td>
				2</td>
			<td>
				<strong>public void run()</strong><br>
				如果该线程是使用独立的&nbsp;Runnable&nbsp;运行对象构造的，则调用该&nbsp;Runnable&nbsp;对象的&nbsp;run&nbsp;方法；否则，该方法不执行任何操作并返回。</td>
		</tr>
		<tr>
			<td>
				3</td>
			<td>
				<strong>public final void setName(String name)</strong><br>
				改变线程名称，使之与参数&nbsp;name&nbsp;相同。</td>
		</tr>
		<tr>
			<td>
				4</td>
			<td>
				<strong>public final void setPriority(int priority)</strong><br>
				&nbsp;更改线程的优先级。</td>
		</tr>
		<tr>
			<td>
				5</td>
			<td>
				<strong>public final void setDaemon(boolean on)</strong><br>
				将该线程标记为守护线程或用户线程。</td>
		</tr>
		<tr>
			<td>
				6</td>
			<td>
				<strong>public final void join(long millisec)</strong><br>
				等待该线程终止的时间最长为&nbsp;millis&nbsp;毫秒。</td>
		</tr>
		<tr>
			<td>
				7</td>
			<td>
				<strong>public void interrupt()</strong><br>
				中断线程。</td>
		</tr>
		<tr>
			<td>
				8</td>
			<td>
				<strong>public final boolean isAlive()</strong><br>
				测试线程是否处于活动状态。</td>
		</tr>
	</tbody>
</table>
<p>上述方法是被 Thread 对象调用的，下面表格的方法是 Thread 类的静态方法。
</p>
<table class="reference">
	<tbody>
		<tr>
			<th>
				<strong>序号</strong></th>
			<th style="text-align: center;">
				<strong>方法描述</strong></th>
		</tr>
		<tr>
			<td>
				1</td>
			<td>
				<strong>public static void yield()</strong><br>
				暂停当前正在执行的线程对象，并执行其他线程。</td>
		</tr>
		<tr>
			<td>
				2</td>
			<td>
				<strong>public static void sleep(long millisec)</strong><br>
				在指定的毫秒数内让当前正在执行的线程休眠（暂停执行），此操作受到系统计时器和调度程序精度和准确性的影响。</td>
		</tr>
		<tr>
			<td>
				3</td>
			<td>
				<strong>public static boolean holdsLock(Object x)</strong><br>
				当且仅当当前线程在指定的对象上保持监视器锁时，才返回&nbsp;true。</td>
		</tr>
		<tr>
			<td>
				4</td>
			<td>
				<strong>public static Thread currentThread()</strong><br>
				返回对当前正在执行的线程对象的引用。</td>
		</tr>
		<tr>
			<td>
				5</td>
			<td>
				<strong>public static void dumpStack()</strong><br>
				将当前线程的堆栈跟踪打印至标准错误流。</td>
		</tr>
	</tbody>
</table>

<h3>实例</h3>
<p>
如下的ThreadClassDemo 程序演示了Thread类的一些方法：
</p>
<div class="example"> 
<h2 class="example">DisplayMessage.java 文件代码：</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">//</span><span class="hl-comment"> 文件名 : DisplayMessage.java</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-comment">//</span><span class="hl-comment"> 通过实现 Runnable 接口创建线程</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">DisplayMessage</span><span class="hl-code"> </span><span class="hl-reserved">implements</span><span class="hl-code"> </span><span class="hl-identifier">Runnable</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
   </span><span class="hl-reserved">private</span><span class="hl-code"> </span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">message</span><span class="hl-code">;
   
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-identifier">DisplayMessage</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">message</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-reserved">this</span><span class="hl-code">.</span><span class="hl-identifier">message</span><span class="hl-code"> = </span><span class="hl-identifier">message</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">run</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-reserved">while</span><span class="hl-brackets">(</span><span class="hl-reserved">true</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-identifier">message</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-brackets">}</span><span class="hl-code">
   </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span></div>
</div><br>
</div>
<div class="example"> 
<h2 class="example">GuessANumber.java 文件代码：</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">//</span><span class="hl-comment"> 文件名 : GuessANumber.java</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-comment">//</span><span class="hl-comment"> 通过继承 Thread 类创建线程</span><span class="hl-comment"></span><span class="hl-code">
 
</span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">GuessANumber</span><span class="hl-code"> </span><span class="hl-reserved">extends</span><span class="hl-code"> </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
   </span><span class="hl-reserved">private</span><span class="hl-code"> </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">number</span><span class="hl-code">;
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-identifier">GuessANumber</span><span class="hl-brackets">(</span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">number</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-reserved">this</span><span class="hl-code">.</span><span class="hl-identifier">number</span><span class="hl-code"> = </span><span class="hl-identifier">number</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">run</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">counter</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">;
      </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">guess</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">;
      </span><span class="hl-reserved">do</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-identifier">guess</span><span class="hl-code"> = </span><span class="hl-brackets">(</span><span class="hl-types">int</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">Math</span><span class="hl-code">.</span><span class="hl-identifier">random</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> * </span><span class="hl-number">100</span><span class="hl-code"> + </span><span class="hl-number">1</span><span class="hl-brackets">)</span><span class="hl-code">;
         </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-reserved">this</span><span class="hl-code">.</span><span class="hl-identifier">getName</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> + </span><span class="hl-quotes">&quot;</span><span class="hl-string"> guesses </span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">guess</span><span class="hl-brackets">)</span><span class="hl-code">;
         </span><span class="hl-identifier">counter</span><span class="hl-code">++;
      </span><span class="hl-brackets">}</span><span class="hl-code"> </span><span class="hl-reserved">while</span><span class="hl-brackets">(</span><span class="hl-identifier">guess</span><span class="hl-code"> != </span><span class="hl-identifier">number</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">** Correct!</span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-reserved">this</span><span class="hl-code">.</span><span class="hl-identifier">getName</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> + </span><span class="hl-quotes">&quot;</span><span class="hl-string">in</span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">counter</span><span class="hl-code"> + </span><span class="hl-quotes">&quot;</span><span class="hl-string">guesses.**</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span></div>
</div><br>
</div>
<div class="example"> 
<h2 class="example">ThreadClassDemo.java 文件代码：</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-comment">//</span><span class="hl-comment"> 文件名 : ThreadClassDemo.java</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">ThreadClassDemo</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
 
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">static</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">main</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-brackets">[</span><span class="hl-brackets">]</span><span class="hl-code"> </span><span class="hl-identifier">args</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">Runnable</span><span class="hl-code"> </span><span class="hl-identifier">hello</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">DisplayMessage</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Hello</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-identifier">thread1</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Thread</span><span class="hl-brackets">(</span><span class="hl-identifier">hello</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">thread1</span><span class="hl-code">.</span><span class="hl-identifier">setDaemon</span><span class="hl-brackets">(</span><span class="hl-reserved">true</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">thread1</span><span class="hl-code">.</span><span class="hl-identifier">setName</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">hello</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Starting hello thread...</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">thread1</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
      
      </span><span class="hl-identifier">Runnable</span><span class="hl-code"> </span><span class="hl-identifier">bye</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">DisplayMessage</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Goodbye</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-identifier">thread2</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Thread</span><span class="hl-brackets">(</span><span class="hl-identifier">bye</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">thread2</span><span class="hl-code">.</span><span class="hl-identifier">setPriority</span><span class="hl-brackets">(</span><span class="hl-identifier">Thread</span><span class="hl-code">.</span><span class="hl-identifier">MIN_PRIORITY</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">thread2</span><span class="hl-code">.</span><span class="hl-identifier">setDaemon</span><span class="hl-brackets">(</span><span class="hl-reserved">true</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Starting goodbye thread...</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">thread2</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
 
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Starting thread3...</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-identifier">thread3</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">GuessANumber</span><span class="hl-brackets">(</span><span class="hl-number">27</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">thread3</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-reserved">try</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-identifier">thread3</span><span class="hl-code">.</span><span class="hl-identifier">join</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-brackets">}</span><span class="hl-reserved">catch</span><span class="hl-brackets">(</span><span class="hl-identifier">InterruptedException</span><span class="hl-code"> </span><span class="hl-identifier">e</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
         </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Thread interrupted.</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-brackets">}</span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Starting thread4...</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">Thread</span><span class="hl-code"> </span><span class="hl-identifier">thread4</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">GuessANumber</span><span class="hl-brackets">(</span><span class="hl-number">75</span><span class="hl-brackets">)</span><span class="hl-code">;
      
      </span><span class="hl-identifier">thread4</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">main() is ending...</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span></div>
</div><br>
</div>
<p>
运行结果如下，每一次运行的结果都不一样。
 </p>
<pre>
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
</pre>

<hr>
<h2>通过 Callable 和 Future 创建线程</h2><ul><li><p>
1. 创建 Callable 接口的实现类，并实现 call() 方法，该 call() 方法将作为线程执行体，并且有返回值。</p></li><li><p>
2. 创建 Callable 实现类的实例，使用 FutureTask 类来包装 Callable 对象，该 FutureTask 对象封装了该 Callable 对象的 call() 方法的返回值。</p></li><li><p>
3. 使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。</p></li><li><p>
4. 调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值。</p></li></ul>
<div class="example"> 
<h2 class="example">实例</h2> 
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">CallableThreadTest</span><span class="hl-code"> </span><span class="hl-reserved">implements</span><span class="hl-code"> </span><span class="hl-identifier">Callable</span><span class="hl-code">&lt;</span><span class="hl-identifier">Integer</span><span class="hl-code">&gt; </span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">static</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">main</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-brackets">[</span><span class="hl-brackets">]</span><span class="hl-code"> </span><span class="hl-identifier">args</span><span class="hl-brackets">)</span><span class="hl-code">  
    </span><span class="hl-brackets">{</span><span class="hl-code">  
        </span><span class="hl-identifier">CallableThreadTest</span><span class="hl-code"> </span><span class="hl-identifier">ctt</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">CallableThreadTest</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;  
        </span><span class="hl-identifier">FutureTask</span><span class="hl-code">&lt;</span><span class="hl-identifier">Integer</span><span class="hl-code">&gt; </span><span class="hl-identifier">ft</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">FutureTask</span><span class="hl-code">&lt;&gt;</span><span class="hl-brackets">(</span><span class="hl-identifier">ctt</span><span class="hl-brackets">)</span><span class="hl-code">;  
        </span><span class="hl-reserved">for</span><span class="hl-brackets">(</span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">i</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">;</span><span class="hl-identifier">i</span><span class="hl-code"> &lt; </span><span class="hl-number">100</span><span class="hl-code">;</span><span class="hl-identifier">i</span><span class="hl-code">++</span><span class="hl-brackets">)</span><span class="hl-code">  
        </span><span class="hl-brackets">{</span><span class="hl-code">  
            </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-identifier">Thread</span><span class="hl-code">.</span><span class="hl-identifier">currentThread</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">.</span><span class="hl-identifier">getName</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">+</span><span class="hl-quotes">&quot;</span><span class="hl-string"> 的循环变量i的值</span><span class="hl-quotes">&quot;</span><span class="hl-code">+</span><span class="hl-identifier">i</span><span class="hl-brackets">)</span><span class="hl-code">;  
            </span><span class="hl-reserved">if</span><span class="hl-brackets">(</span><span class="hl-identifier">i</span><span class="hl-code">==</span><span class="hl-number">20</span><span class="hl-brackets">)</span><span class="hl-code">  
            </span><span class="hl-brackets">{</span><span class="hl-code">  
                </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Thread</span><span class="hl-brackets">(</span><span class="hl-identifier">ft</span><span class="hl-code">,</span><span class="hl-quotes">&quot;</span><span class="hl-string">有返回值的线程</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">.</span><span class="hl-identifier">start</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;  
            </span><span class="hl-brackets">}</span><span class="hl-code">  
        </span><span class="hl-brackets">}</span><span class="hl-code">  
        </span><span class="hl-reserved">try</span><span class="hl-code">  
        </span><span class="hl-brackets">{</span><span class="hl-code">  
            </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">子线程的返回值：</span><span class="hl-quotes">&quot;</span><span class="hl-code">+</span><span class="hl-identifier">ft</span><span class="hl-code">.</span><span class="hl-identifier">get</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">;  
        </span><span class="hl-brackets">}</span><span class="hl-code"> </span><span class="hl-reserved">catch</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">InterruptedException</span><span class="hl-code"> </span><span class="hl-identifier">e</span><span class="hl-brackets">)</span><span class="hl-code">  
        </span><span class="hl-brackets">{</span><span class="hl-code">  
            </span><span class="hl-identifier">e</span><span class="hl-code">.</span><span class="hl-identifier">printStackTrace</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;  
        </span><span class="hl-brackets">}</span><span class="hl-code"> </span><span class="hl-reserved">catch</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">ExecutionException</span><span class="hl-code"> </span><span class="hl-identifier">e</span><span class="hl-brackets">)</span><span class="hl-code">  
        </span><span class="hl-brackets">{</span><span class="hl-code">  
            </span><span class="hl-identifier">e</span><span class="hl-code">.</span><span class="hl-identifier">printStackTrace</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;  
        </span><span class="hl-brackets">}</span><span class="hl-code">  
  
    </span><span class="hl-brackets">}</span><span class="hl-code">
    @</span><span class="hl-identifier">Override</span><span class="hl-code">  
    </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-identifier">Integer</span><span class="hl-code"> </span><span class="hl-identifier">call</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-reserved">throws</span><span class="hl-code"> </span><span class="hl-identifier">Exception</span><span class="hl-code">  
    </span><span class="hl-brackets">{</span><span class="hl-code">  
        </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">i</span><span class="hl-code"> = </span><span class="hl-number">0</span><span class="hl-code">;  
        </span><span class="hl-reserved">for</span><span class="hl-brackets">(</span><span class="hl-code">;</span><span class="hl-identifier">i</span><span class="hl-code">&lt;</span><span class="hl-number">100</span><span class="hl-code">;</span><span class="hl-identifier">i</span><span class="hl-code">++</span><span class="hl-brackets">)</span><span class="hl-code">  
        </span><span class="hl-brackets">{</span><span class="hl-code">  
            </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-identifier">Thread</span><span class="hl-code">.</span><span class="hl-identifier">currentThread</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">.</span><span class="hl-identifier">getName</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">+</span><span class="hl-quotes">&quot;</span><span class="hl-string"> </span><span class="hl-quotes">&quot;</span><span class="hl-code">+</span><span class="hl-identifier">i</span><span class="hl-brackets">)</span><span class="hl-code">;  
        </span><span class="hl-brackets">}</span><span class="hl-code">  
        </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-identifier">i</span><span class="hl-code">;  
    </span><span class="hl-brackets">}</span><span class="hl-code">  
</span><span class="hl-brackets">}</span></div>
</div><br>
</div>
<hr>
<h2>创建线程的三种方式的对比</h2>
<ul>
<li><p>1. 采用实现 Runnable、Callable 接口的方式创建多线程时，线程类只是实现了 Runnable 接口或 Callable 接口，还可以继承其他类。</p></li><li><p>
2. 使用继承 Thread 类的方式创建多线程时，编写简单，如果需要访问当前线程，则无需使用 Thread.currentThread() 方法，直接使用 this 即可获得当前线程。</p>
</li></ul>
<hr>
<h2>线程的几个主要概念
</h2>
<p>
在多线程编程时，你需要了解以下几个概念：</p>
<ul>
<li>
线程同步</li><li>
线程间通信</li><li>
线程死锁</li><li>
线程控制：挂起、停止和恢复</li></ul>
<hr><h2>多线程的使用</h2>
<p>
有效利用多线程的关键是理解程序是并发执行而不是串行执行的。例如：程序中有两个子系统需要并发执行，这时候就需要利用多线程编程。</p><p>
通过对多线程的使用，可以编写出非常高效的程序。不过请注意，如果你创建太多的线程，程序执行的效率实际上是降低了，而不是提升了。</p><p>
请记住，上下文的切换开销也很重要，如果你创建了太多的线程，CPU 花费在上下文的切换的时间将多于执行程序的时间！</p>			<!-- 其他扩展 -->
						
			</div>
			
		</div>
		
		<div class="previous-next-links">
			<div class="previous-design-link"><i style="font-size:16px;" class="fa fa-arrow-left" aria-hidden="true"></i> <a href="../java/java-sending-email.html" rel="prev"> Java 发送邮件</a> </div>
			<div class="next-design-link"><a href="../java/java-applet-basics.html" rel="next"> Java Applet 基础</a> <i style="font-size:16px;" class="fa fa-arrow-right" aria-hidden="true"></i></div>
		</div>
		<!-- 笔记列表 -->
		<style>
.wrapper {
  /*text-transform: uppercase; */
  background: #ececec;
  color: #555;
  cursor: help;
  font-family: "Gill Sans", Impact, sans-serif;
  font-size: 20px;
  position: relative;
  text-align: center;
  width: 200px;
  -webkit-transform: translateZ(0); /* webkit flicker fix */
  -webkit-font-smoothing: antialiased; /* webkit text rendering fix */
}

.wrapper .tooltip {
  white-space: nowrap;
  font-size: 14px;
  text-align: left;
  background: #96b97d;
  bottom: 100%;
  color: #fff;
  display: block;
  left: -25px;
  margin-bottom: 15px;
  opacity: 0;
  padding: 14px;
  pointer-events: none;
  position: absolute;
  
  -webkit-transform: translateY(10px);
     -moz-transform: translateY(10px);
      -ms-transform: translateY(10px);
       -o-transform: translateY(10px);
          transform: translateY(10px);
  -webkit-transition: all .25s ease-out;
     -moz-transition: all .25s ease-out;
      -ms-transition: all .25s ease-out;
       -o-transition: all .25s ease-out;
          transition: all .25s ease-out;
  -webkit-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
     -moz-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
      -ms-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
       -o-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
          box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
}
.tooltip a {
	color:#fff;
}
/* This bridges the gap so you can mouse into the tooltip without it disappearing */
.wrapper .tooltip:before {
  bottom: -20px;
  content: " ";
  display: block;
  height: 20px;
  left: 0;
  position: absolute;
  width: 100%;
}  

/* CSS Triangles - see Trevor's post */
.wrapper .tooltip:after {
  border-left: solid transparent 10px;
  border-right: solid transparent 10px;
  border-top: solid #96b97d 10px;
  bottom: -10px;
  content: " ";
  height: 0;
  left: 20%;
  margin-left: -13px;
  position: absolute;
  width: 0;
}
.wrapper .tooltip1 {
	margin-left: 50px;
	padding-top: 0px;
}
/*
.wrapper:hover .tooltip {
  opacity: 1;
  pointer-events: auto;
  -webkit-transform: translateY(0px);
     -moz-transform: translateY(0px);
      -ms-transform: translateY(0px);
       -o-transform: translateY(0px);
          transform: translateY(0px);
}
*/
/* IE can just show/hide with no transition */
.lte8 .wrapper .tooltip {
  display: none;
}

.lte8 .wrapper:hover .tooltip {
  display: block;
}

</style>

<link rel="stylesheet" href="../0/upvotejs.css">
<script src=""></script>
<script src=""></script>
<div class="title" id="comments">
	<h2 class="">
    <div class="altblock">
				<i style="font-size:28px;margin-top: 8px;" class="fa fa-plus-square" aria-hidden="true"></i>
		    </div>
    <span class="mw-headline" id="qa_headline">8  篇笔记</span>
	<span class="mw-headline" id="user_add_note" style="float:right;line-height: 62px;padding-right: 14px;"><i class="fa fa-pencil-square-o" aria-hidden="true"></i>  写笔记</span>
    </h2>
</div>

<div id="postcomments"  style="display:none;" >
	<ol class="commentlist">
		<li class="comment even thread-even depth-1" id="comment-24578"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;dg5uw</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;159***75112@139.com</p></div><div id="runoobvote-id-24578" data-commid = "24578" class="upvotejs"><a class="upvote"></a> <span class="count">161</span></div></div><div class="comt-main" id="div-comment-24578"><h2>线程池</h2>

<p>1、线程池，其实就是一个容纳多个线程的容器，其中的线程可以反复使用，省去了频繁创建线程对象的操作，无需反复创建线程而消耗过多资源。（是什么）</p>

<p>2、那么，我们为什么需要用到线程池呢？每次用的时候手动创建不行吗？</p>

<p>在java中，如果每个请求到达就创建一个新线程，开销是相当大的。在实际使用中，创建和销毁线程花费的时间和消耗的系统资源都相当大，甚至可能要比在处理实际的用户请求的时间和资源要多的多。除了创建和销毁线程的开销之外，活动的线程也需要消耗系统资源。如果在一个jvm里创建太多的线程，可能会使系统由于过度消耗内存或“切换过度”而导致系统资源不足。为了防止资源不足，需要采取一些办法来限制任何给定时刻处理的请求数目，尽可能减少创建和销毁线程的次数，特别是一些资源耗费比较大的线程的创建和销毁，尽量利用已有对象来进行服务。（为什么）</p>

<p>线程池主要用来解决线程生命周期开销问题和资源不足问题。通过对多个任务重复使用线程，线程创建的开销就被分摊到了多个任务上了，而且由于在请求到达时线程已经存在，所以消除了线程创建所带来的延迟。这样，就可以立即为请求服务，使用应用程序响应更快；另外，通过适当的调整线程中的线程数目可以防止出现资源不足的情况。（什么用）</p>

<p>3、线程池都是通过线程池工厂创建，再调用线程池中的方法获取线程，再通过线程去执行任务方法。        </p>
<ul><li>
<span class="marked">Executors</span>：线程池创建工厂类</li><li>
<span class="marked">public static ExecutorServicenewFixedThreadPool(int nThreads)</span>：返回线程池对象</li><li>
<span class="marked">ExecutorService</span>：线程池类</li><li>
<span class="marked">Future&lt;?&gt; submit(Runnable task)</span>：获取线程池中的某一个线程对象，并执行</li><li>
<span class="marked">Future 接口</span>：用来记录线程任务执行完毕后产生的结果。线程池创建与使用</li></ul>


<p>4、这里介绍两种使用线程池创建线程的方法</p>

<p><strong>1）：使用Runnable接口创建线程池</strong></p>

<p>使用线程池中线程对象的步骤：</p>
<ul><li>
1、创建线程池对象</li><li>
2、创建 Runnable 接口子类对象</li><li>
3、提交 Runnable 接口子类对象</li><li>
4、关闭线程池</li></ul>

<p><strong>Test.java</strong> 代码如下：</p>
<pre>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    public static void main(String[] args) {
        //创建线程池对象  参数5，代表有5个线程的线程池
        ExecutorService service = Executors.newFixedThreadPool(5);
        //创建Runnable线程任务对象
        TaskRunnable task = new TaskRunnable();
        //从线程池中获取线程对象
        service.submit(task);
        System.out.println("----------------------");
        //再获取一个线程对象
        service.submit(task);
        //关闭线程池
        service.shutdown();
    }
}</pre>
<p>TaskRunnable.java  接口文件如下：</p>
<pre>public class TaskRunnable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i &lt; 1000; i++) {
            System.out.println("自定义线程任务在执行"+i);
        }
    }
}</pre>
<p>2）使用Callable接口创建线程池</p>
<p>Callable接口：与Runnable接口功能相似，用来指定线程的任务。其中的call()方法，用来返回线程任务执行完毕后的结果，call方法可抛出异常。</p>

<p><span class="marked">ExecutorService</span>：线程池类</p>

<p><span class="marked">&lt;T&gt; Future&lt;T&gt; submit(Callable&lt;T&gt; task)</span>：获取线程池中的某一个线程对象，并执行线程中的 call() 方法</p>

<p><span class="marked">Future 接口</span>：用来记录线程任务执行完毕后产生的结果。线程池创建与使用</p>
<p>
使用线程池中线程对象的步骤：</p>
<ul><li>
1、创建线程池对象
</li><li>
2、创建 Callable 接口子类对象
</li><li>
3、提交 Callable 接口子类对象
</li><li>
4、关闭线程池
</li></ul>
<p>Test.java 代码如下：</p>

<pre>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test{
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(3);
        TaskCallable c = new TaskCallable();
        //线程池中获取线程对象，调用run方法
        service.submit(c);
        //再获取一个
        service.submit(c);
        //关闭线程池
        service.shutdown();
    }
}</pre>

<p>TaskCallable.java  接口文件如下：</p>
<pre>import java.util.concurrent.Callable;

public class TaskCallable implements Callable&lt;Object&gt;{
    @Override
    public Object call() throws Exception {
        for (int i = 0; i &lt; 1000; i++) {
            System.out.println("自定义线程任务在执行"+i);
        }
        return null;
    }
}</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">dg5uw</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;dg5uw</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;159***75112@139.com</p></div></span>5年前 (2018-03-05)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-24579"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;dg5uw</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;159***75112@139.com</p></div><div id="runoobvote-id-24579" data-commid = "24579" class="upvotejs"><a class="upvote"></a> <span class="count">45</span></div></div><div class="comt-main" id="div-comment-24579">



<p><strong>线程池练习：返回两个数相加的结果</strong></p>
<p>要求：通过线程池中的线程对象，使用Callable接口完成两个数求和操作</p>

<p><strong>Future 接口</strong>：用来记录线程任务执行完毕后产生的结果。</p>
<p><strong>线程池创建与使用</strong>：get() 获取 Future对象中封装的数据结果</p>

<p>ThreadPoolDemo.java 文件代码如下：</p>
<pre>import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPoolDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //创建线程池对象
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        
        //创建一个Callable接口子类对象
        //MyCallable c = new MyCallable();
        MyCallable c = new MyCallable(100, 200);
        MyCallable c2 = new MyCallable(10, 20);
        
        //获取线程池中的线程，调用Callable接口子类对象中的call()方法, 完成求和操作
        //&lt;Integer&gt; Future&lt;Integer&gt; submit(Callable&lt;Integer&gt; task)
        // Future 结果对象
        Future&lt;Integer&gt; result = threadPool.submit(c);
        //此 Future 的 get 方法所返回的结果类型
        Integer sum = result.get();
        System.out.println("sum=" + sum);
        
        //再演示
        result = threadPool.submit(c2);
        sum = result.get();
        System.out.println("sum=" + sum);
        //关闭线程池(可以不关闭)
        
    }
}</pre>

<p>MyCallable.java 接口文件代码如下：</p>

<pre>import java.util.concurrent.Callable;

public class MyCallable implements Callable&lt;Integer&gt; {
    //成员变量
    int x = 5;
    int y = 3;
    //构造方法
    public MyCallable(){
    }
    public MyCallable(int x, int y){
        this.x = x;
        this.y = y;
    }

    @Override
    public Integer call() throws Exception {
        return x+y;
    }
}</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">dg5uw</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;dg5uw</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;159***75112@139.com</p></div></span>5年前 (2018-03-05)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-25412"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;0℃space</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;960***125@qq.com</p></div><div id="runoobvote-id-25412" data-commid = "25412" class="upvotejs"><a class="upvote"></a> <span class="count">29</span></div></div><div class="comt-main" id="div-comment-25412"><p><b>进程和线程的区别</b></p><p>	进程</p><p>应用程序的执行实例，有独立的内存空间和系统资源</p><p>		</p><p>	线程</p><p>CPU调度和分派的基本单位，进程中执行运算的最小单位，可完成一个独立的顺序控制流程</p><p><b>进程和线程的关系</b></p><p>（1）一个线程只能属于一个进程，而一个进程可以有多个线程，但至少有一个线程。线程是操作系统可识别的最小执行和调度单位。</p><p>（2）资源分配给进程，同一进程的所有线程共享该进程的所有资源。 同一进程中的多个线程共享代码段(代码和常量)，数据段(全局变量和静态变量)，扩展段(堆存储)。但是每个线程拥有自己的栈段，栈段又叫运行时段，用来存放所有局部变量和临时变量。</p><p>（3）处理机分给线程，即真正在处理机上运行的是线程。</p><p>（4）线程在执行过程中，需要协作同步。不同进程的线程间要利用消息通信的办法实现同步。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">0℃space</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;0℃space</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;960***125@qq.com</p></div></span>5年前 (2018-03-23)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-33934"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;阿颖</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;553***793@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://blog.csdn.net/xuxurui007/article/details/7685076">&nbsp;&nbsp;参考地址</a></p></div><div id="runoobvote-id-33934" data-commid = "33934" class="upvotejs"><a class="upvote"></a> <span class="count">35</span></div></div><div class="comt-main" id="div-comment-33934"><p data-title="Java Thread 中 run() 与 start() 的区别"><strong>Java Thread 中 run() 与 start() 的区别</strong></p>

<p>Java 的线程是通过 java.lang.Thread 类来实现的。VM 启动时会有一个由主方法所定义的线程。可以通过创建 Thread 的实例来创建新的线程。每个线程都是通过某个特定 Thread 对象所对应的方法 run() 来完成其操作的，方法 run() 称为线程体。通过调用 Thread 类的 start() 方法来启动一个线程。</p>


<p>在 Java 当中，线程通常都有五种状态，创建、就绪、运行、阻塞和死亡。</p>
<ul><li>
第一是创建状态。在生成线程对象，并没有调用该对象的 start 方法，这是线程处于创建状态。
</li><li>第二是就绪状态。当调用了线程对象的 start 方法之后，该线程就进入了就绪状态，但是此时线程调度程序还没有把该线程设置为当前线程，此时处于就绪状态。在线程运行之后，从等待或者睡眠中回来之后，也会处于就绪状态。
</li><li>第三是运行状态。线程调度程序将处于就绪状态的线程设置为当前线程，此时线程就进入了运行状态，开始运行 run 函数当中的代码。
</li><li>第四是阻塞状态。线程正在运行的时候，被暂停，通常是为了等待某个时间的发生(比如说某项资源就绪)之后再继续运行。sleep,suspend，wait 等方法都可以导致线程阻塞。
</li><li>第五是死亡状态。如果一个线程的 run 方法执行结束或者调用 stop 方法后，该线程就会死亡。对于已经死亡的线程，无法再使用 start 方法令其进入就绪。</li></ul>

<p><strong>实现并启动线程有两种方法</strong></p>
<ul><li>
1、写一个类继承自 Thread 类，重写 run 方法。用 start 方法启动线程</li><li>
2、写一个类实现 Runnable 接口，实现 run 方法。用 new Thread(Runnable target).start() 方法来启动
</li></ul>
<p><strong>多线程原理：</strong>相当于玩游戏机，只有一个游戏机（cpu），可是有很多人要玩，于是，start 是排队！等 CPU 选中你就是轮到你，你就 run()，当 CPU 的运行的时间片执行完，这个线程就继续排队，等待下一次的run()。</p>

<p>调用 start() 后，线程会被放到等待队列，等待 CPU 调度，并不一定要马上开始执行，只是将这个线程置于可动行状态。然后通过 JVM，线程 Thread 会调用 run() 方法，执行本线程的线程体。先调用 start 后调用 run，这么麻烦，为了不直接调用 run？就是为了实现多线程的优点，没这个 start 不行。</p>
<ul><li>
<strong>1.start() </strong>方法来启动线程，真正实现了多线程运行。这时无需等待 run 方法体代码执行完毕，可以直接继续执行下面的代码；通过调用 Thread 类的 start() 方法来启动一个线程， 这时此线程是处于就绪状态， 并没有运行。 然后通过此 Thread 类调用方法 run() 来完成其运行操作的， 这里方法 run() 称为线程体，它包含了要执行的这个线程的内容， run 方法运行结束， 此线程终止。然后 CPU 再调度其它线程。
</li><li><strong>2.run()</strong> 方法当作普通方法的方式调用。程序还是要顺序执行，要等待 run 方法体执行完毕后，才可继续执行下面的代码； 程序中只有主线程——这一个线程， 其程序执行路径还是只有一条， 这样就没有达到写线程的目的。
</li></ul>
<p><strong>记住：</strong>多线程就是分时利用 CPU，宏观上让所有线程一起执行 ，也叫并发。</p>

<pre>public class Test {
    public static void main(String[] args) {
        Runner1 runner1 = new Runner1();
        Runner2 runner2 = new Runner2();
//        Thread(Runnable target) 分配新的 Thread 对象。
        Thread thread1 = new Thread(runner1);
        Thread thread2 = new Thread(runner2);
//        thread1.start();
//        thread2.start();
        thread1.run();
        thread2.run();
    }
}
 
class Runner1 implements Runnable { // 实现了Runnable接口，jdk就知道这个类是一个线程
    public void run() {
        for (int i = 0; i &lt; 100; i++) {
            System.out.println("进入Runner1运行状态&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;" + i);
        }
    }
}
 
class Runner2 implements Runnable { // 实现了Runnable接口，jdk就知道这个类是一个线程
    public void run() {
        for (int i = 0; i &lt; 100; i++) {
            System.out.println("进入Runner2运行状态==========" + i);
        }
    }
}</pre>
<div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="../note/33934">阿颖</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;阿颖</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;553***793@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://blog.csdn.net/xuxurui007/article/details/7685076">&nbsp;&nbsp;参考地址</a></p></div></span>5年前 (2018-08-13)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-34745"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;HelloWorld</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;zhy***@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://www.cnblogs.com/happy-coder/p/6587092.html">&nbsp;&nbsp;参考地址</a></p></div><div id="runoobvote-id-34745" data-commid = "34745" class="upvotejs"><a class="upvote"></a> <span class="count">27</span></div></div><div class="comt-main" id="div-comment-34745"><p data-title="Java 线程的 5 种状态">线程状态图：</p>
<p><img src="//www.runoob.com/wp-content/uploads/2014/09/716271-20170320112245721-1831918220.jpg"></p>

线程共包括以下 5 种状态:
<p><strong>1. 新建状态(New):</strong> 线程对象被创建后，就进入了新建状态。例如，Thread thread = new Thread()。</p>
<p><strong>2. 就绪状态(Runnable):</strong> 也被称为“可执行状态”。线程对象被创建后，其它线程调用了该对象的start()方法，从而来启动该线程。例如，thread.start()。处于就绪状态的线程，随时可能被CPU调度执行。</p>
<p><strong>3. 运行状态(Running):</strong> 线程获取CPU权限进行执行。需要注意的是，线程只能从就绪状态进入到运行状态。</p>
<p><strong>4. 阻塞状态(Blocked):</strong> 阻塞状态是线程因为某种原因放弃CPU使用权，暂时停止运行。直到线程进入就绪状态，才有机会转到运行状态。阻塞的情况分三种：</p>
<ul><li>
(01) 等待阻塞 -- 通过调用线程的wait()方法，让线程等待某工作的完成。</li><li>
(02) 同步阻塞 -- 线程在获取synchronized同步锁失败(因为锁被其它线程所占用)，它会进入同步阻塞状态。</li><li>
(03) 其他阻塞 -- 通过调用线程的sleep()或join()或发出了I/O请求时，线程会进入到阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时，线程重新转入就绪状态。</li></ul>
<p><strong>5. 死亡状态(Dead):</strong> 线程执行完了或者因异常退出了run()方法，该线程结束生命周期。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="../note/34745">HelloWorld</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;HelloWorld</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;zhy***@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://www.cnblogs.com/happy-coder/p/6587092.html">&nbsp;&nbsp;参考地址</a></p></div></span>5年前 (2018-09-04)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-36637"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;cz</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;109***3594@qq.com</p></div><div id="runoobvote-id-36637" data-commid = "36637" class="upvotejs"><a class="upvote"></a> <span class="count">30</span></div></div><div class="comt-main" id="div-comment-36637"><p><strong>线程安全问题</strong></p>

<p><strong>产生原因：</strong>多个线程竞争同一资源（访问同一数据），可参考经典的生产者消费者问题。</p>

<p>解决方案：</p>

<p>run 方法内：同步代码块<strong> synchronized {}</strong></p>

<pre>Public synchronized 返回值类型 方法名（）{} 自动释放对象锁</pre>

<p><strong>使用 Lock 锁</strong></p>

<p>Lock 锁需要程序员（在 finally 代码块中）手动释放。</p>

<pre>Lock lock=new ReentranttLock()    // Reentrant（可重用的）</pre>





<p>Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的锁定操作，是 JDK1.5 之后出现的。</p>



<p>Lock 接口中的方法:</p>
<pre>void lock()   // 获取锁 
void unlock() // 释放锁 </pre>

<p>Lock 接口的实现类:</p>

<pre>java.util.concurrent.locks.ReentrantLock implements Lock</pre>

<p>使用步骤:</p>
<ul><li>
1.在成员位置创建一个 ReentrantLock 对象。
</li><li>
2.在可能出现线程安全问题的代码前，调用 Lock 接口中的方法 lock 获取锁对象。
</li><li>
3.在可能出现线程安全问题的代码后，调用 Lock 接口中的方法 unlock 释放锁对象。
</li></ul>


<pre>public class RunnableImpl implements Runnable{
    //定义一个共享的票源
    private int ticket = 100;
    //1.在成员位置创建一个ReentrantLock对象
    Lock l = new ReentrantLock();
    //设置线程任务:卖票
    @Override
    public void run() {
        //使用死循环,让卖票重复的执行
        while(true){
            //2.在可能出现线程安全问题的代码前,调用Lock接口中的方法lock获取锁对象
            l.lock();
            //判断票是否大于0
            if(ticket&gt;0){
                //为了提高线程安全问题出现的几率,让程序睡眠10毫秒
                try {
                    //可能会产生异常的代码
                    Thread.sleep(10);
                    //进行卖票 ticket--
                    System.out.println(Thread.currentThread().getName()+"正在卖第"+ticket+"张票!");
                    ticket--;
                } catch (InterruptedException e) {
                    //异常的处理逻辑
                    e.printStackTrace();
                }finally {
                    //一定会执行的代码,一般用于资源释放(资源回收)
                    //3.在可能出现线程安全问题的代码后,调用Lock接口中的方法unlock释放锁对象
                    l.unlock();//无论程序是否有异常,都让锁对象释放掉,节约内存,提高程序的效率
                }
            }
        }
    }
}</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">cz</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;cz</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;109***3594@qq.com</p></div></span>5年前 (2018-11-06)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-43527"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;我v成为v我v成为</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;201***6216@qq.com</p></div><div id="runoobvote-id-43527" data-commid = "43527" class="upvotejs"><a class="upvote"></a> <span class="count">24</span></div></div><div class="comt-main" id="div-comment-43527"><p>用 CompletableFuture 来解决回调的问题。</p>

<pre>import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;

public class CompletableFutureDemo {
    public static void main(String[] args) throws InterruptedException {
        long l = System.currentTimeMillis();
        CompletableFuture&lt;Integer&gt; completableFuture = CompletableFuture.supplyAsync(() -&gt; {
            System.out.println("执行耗时操作...");
            timeConsumingOperation();
            return 100;
        });
        completableFuture.whenComplete((result, e) -&gt; {
            System.out.println("结果：" + result);
        });
        System.out.println("主线程运算耗时:" + (System.currentTimeMillis() - l) + " ms");
        new CountDownLatch(1).await();
    }

    static void timeConsumingOperation() {
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}</pre>

<p>控制台输出：</p>

<pre>执行耗时操作...
主线程运算耗时:74 ms
结果：100</pre>

<p>可以发现耗时操作没有占用主线程的时间片，达到了异步调用的效果。我们也不需要引入任何第三方的依赖，这都是依赖于 java.util.concurrent.CompletableFuture 的出现。CompletableFuture 提供了近 50 多个方法，大大便捷了 java 多线程操作，和异步调用的写法。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">我v成为v我v成为</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;我v成为v我v成为</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;201***6216@qq.com</p></div></span>4年前 (2019-06-11)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-51824"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;八云式</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;139***2520@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://blog.csdn.net/qq_38293564/article/details/80432875">&nbsp;&nbsp;参考地址</a></p></div><div id="runoobvote-id-51824" data-commid = "51824" class="upvotejs"><a class="upvote"></a> <span class="count">24</span></div></div><div class="comt-main" id="div-comment-51824"><p>关于java的多线程，这里补充一下Object类的线程方法。</p><p>notify()&nbsp;：通知一个在对象上等待的线程，使其从wait()返回，而返回的前提是该线程获取到了对象的锁。</p><p>notifyAll()：	通知所有等待在该对象上的线程。</p><p>wait()：调用该方法的线程进入WAITING状态，只有等待另外线程的通知或被中断才会返回，需要注意，</p><p>调用wait()方法后，会释放对象的锁。</p><p>wait(long) ：超时等待一段时间，这里的参数是毫秒，也就是等待长达n毫秒，如果没有通知就超时返回。</p><p>wait(long, int) ：	对于超时时间更细粒度的控制，可以达到毫秒。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">八云式</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;八云式</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;139***2520@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://blog.csdn.net/qq_38293564/article/details/80432875">&nbsp;&nbsp;参考地址</a></p></div></span>3年前 (2020-03-21)</div></div></li><!-- #comment-## -->
	</ol>
	<div class="pagenav">
			</div>
</div>
<div id="respond" class="no_webshot"> 
		<div class="comment-signarea" style="display:none; padding: 20px 20px;"> 
	<h3 class="text-muted" id="share_code" style="color: #799961;"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> 点我分享笔记</h3>
	<!--
	<p style="font-size:14px;">笔记需要是本篇文章的内容扩展！</p><br>
	<p style="font-size:12px;"><a href="../tougao" target="_blank">文章投稿，可点击这里</a></p>
	<p style="font-size:14px;"><a href="../w3cnote/runoob-user-test-intro.html#invite" target="_blank">注册邀请码获取方式</a></p>
		<h3 class="text-muted"><i class="fa fa-info-circle" aria-hidden="true"></i> 分享笔记前必须<a href="javascript:;" class="runoob-pop">登录</a>！</h3>
		<p><a href="../w3cnote/runoob-user-test-intro.html#invite" target="_blank">注册邀请码获取方式</a></p>-->
	</div>
		
	<form action="/wp-content/themes/runoob/option/addnote.php" method="post" id="commentform" style="display:none;">
		<div class="comt">
			<div class="comt-title">
				<i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i>				<p><a id="cancel-comment-reply-link" href="javascript:;">取消</a></p>
			</div>
			<div class="comt-box">
			<div id="mded"></div>
			
				<div class="comt-ctrl">
					<div class="comt-tips"><input type='hidden' name='comment_post_ID' value='5138' id='comment_post_ID' />
<input type='hidden' name='comment_parent' id='comment_parent' value='0' />
</div>
					<button type="submit" name="submit" id="submit" tabindex="5"><i class="fa fa-pencil" aria-hidden="true"></i> 分享笔记</button>
				</div>
			</div>
		
				
					<div class="comt-comterinfo"> 
						<ul id="comment-author-info">
							<li class="form-inline"><label class="hide" for="author">昵称</label><input class="ipt" type="text" name="author" id="author" value="" tabindex="2" placeholder="昵称"><span class="text-muted">昵称 (必填)</span></li>
							<li class="form-inline"><label class="hide" for="email">邮箱</label><input class="ipt" type="text" name="email" id="email" value="" tabindex="3" placeholder="邮箱"><span class="text-muted">邮箱 (必填)</span></li>
							<li class="form-inline"><label class="hide" for="url">引用地址</label><input class="ipt" type="text" name="url" id="url" value="" tabindex="4" placeholder="引用地址"><span class="text-muted">引用地址</span></li>
						</ul>
					</div>
				
			
		</div>

	</form>
	</div>
<script type="text/javascript">
$(function() {
	//初始化编辑器
	
	var editor = new Simditor({
	  textarea: $('#mded'),
	  placeholder: '写笔记...',
	  upload:false,
	 // upload: {url:'/api/comment_upload_file.php',params: null,fileKey: 'upload_file',connectionCount: 1,leaveConfirm: '文件正在上传，您确定离开?'},
	  defaultImage: 'https://www.runoob.com/images/logo.png',
	  codeLanguages: '',
	  autosave: 'editor-content',
	  toolbar: [  'bold','code','ul','ol','image' ]
	});
	editor.on('selectionchanged', function() {
		$(".code-popover").hide();
	});

	// 提交数据
	$("#share_code").click(function() {
		$(".comment-signarea").hide();
		$("#commentform").show();
		
	});
	$("#user_add_note").click(function() {
		$(".comment-signarea").hide();
		$("#commentform").show();
		$('html, body').animate({
       	    scrollTop: $("#respond").offset().top
    	}, 200);
	});

	// 提交笔记
	var commentform=$('#commentform');
	commentform.prepend('<div id="comment-status" style="display:none;" ></div>');
	var statusdiv=$('#comment-status');
	
	commentform.submit(function(e){
		e.preventDefault();
		var noteContent = editor.getValue();
		// console.log(noteContent);
		noteContent = noteContent.replace(/<pre><code>/g,"<pre>");
		noteContent = noteContent.replace(/<\/code><\/pre>/g,"</pre>");
		
		// 系列化表单数据
		var comment_parent = 0;
		var is_user_logged_in = $("#is_user_logged_in").val();
		var comment_post_ID =  5138;
		var _wp_unfiltered_html_comment = $("#_wp_unfiltered_html_comment").val();
		var comment = noteContent;
		var author = $("#author").val();
		var url = $("#url").val();
		var email = $("#email").val();
		if(isBlank(author) && is_user_logged_in==0) {
			statusdiv.html('<p  class="ajax-error">请输入昵称！</p>').show();
		} else if(isBlank(email)  && is_user_logged_in==0) {
			statusdiv.html('<p  class="ajax-error">请输入邮箱！</p>').show();
		} else {
			// var formdata=commentform.serialize() + "&comment=" + noteContent ;
			// 添加状态信息
			statusdiv.html('<p>Processing...</p>').show();
			// 获取表单提交地址
			var formurl=commentform.attr('action');
			
			// 异步提交
			$.ajax({
					type: 'post',
					url: formurl,
					dataType:'json',
					data: {"comment_parent":comment_parent,"comment_post_ID":comment_post_ID, "_wp_unfiltered_html_comment":_wp_unfiltered_html_comment,"comment":comment,"url":url, "email":email,"author":author},
					error: function(XMLHttpRequest, textStatus, errorThrown){
					statusdiv.html('<p class="ajax-error" >数据不完整或表单提交太快了！</p>').show();
				},
				success: function(data, textStatus){
					if(data.errorno=="0") {
						$("#submit").prop('disabled', true);
						statusdiv.html('<p class="ajax-success" >笔记已提交审核，感谢分享笔记！</p>').show();
						alert('笔记已提交审核，感谢分享笔记！');
					}else{
						statusdiv.html('<p class="ajax-error" >'+data.msg+'</p>').show();
					}
					commentform.find('textarea[name=comment]').val('');
				}
			});
			setTimeout(function(){
		        $("#submit").prop('disabled', false);
		    }, 10*1000);
		}
		return false;

	});
	$(".comt-author").click(function() {
		href = $(this).children("a").attr("href");
		if(href.indexOf("/note/")!=-1) {
			var win = window.open(href, '_blank');
  			win.focus();
		}
	});
	$(".comt-meta span").hover(function(){
		$(this).children(".tooltip").css({ "opacity": 1, "pointer-events": "auto"});
	},function(){
		$(this).children(".tooltip").removeAttr("style");
	});
	/*
	$(".wrapper i").hover(function(){
		$(this).siblings(".tooltip").css({ "opacity": 1, "pointer-events": "auto"});
	},function(){
		$(this).siblings(".tooltip").css({ "opacity": 0, "pointer-events": "auto"});
	});
	*/
	//Upvote.create('runoobvote-id', {callback: vote_callback});
	var ajaxurl = 'https://www.runoob.com/wp-admin/admin-ajax.php';
	var callback = function(data) {
		//console.log($('#runoobvote-id').upvote('upvoted'));
		//console.log($('#runoobvote-id').upvote('downvoted'));
		//console.log(data);
		_vote_action = data.action;
		id_arr = data.id.split('-');
		um_id= id_arr[2];
		//console.log(um_id);
		
		var re = /^[1-9]+/;
		if (re.test(um_id)) { 
			var ajax_data = {
				_vote_action: _vote_action,
				action: "pinglun_zan",
				um_id: um_id,
				um_action: "ding"
			};
			//console.log(ajax_data);
			$.post(ajaxurl,ajax_data,function(status){
				//if(status.vote_num>999) {
				//	_voteHtml = '<span style="display: block; text-align: center;font-size: 20px; color: #6a737c; margin: 8px 0;">'+kFormatter(status.vote_num) +'</span>';
				//	$("#runoobvote-id-" + um_id + " .count").hide().after(_voteHtml);
				//}
				
			});
		}
	};
	if($('#comments').length && $('.upvotejs').length){
		$('.upvotejs').upvote({id: 5138, callback: callback});
	
		$.post(ajaxurl,{"action":"pinglun_zan","postid":5138},function(data){  
			$(data).each(function(key,value) {
				$("#runoobvote-id-" + value.commid + " .upvote").addClass(value.upvotejs_class);
				$("#runoobvote-id-" + value.commid + " .downvote").addClass(value.downvote_class);
				$("#runoobvote-id-" + value.commid + " .count").text(value.upvote_count);
			})
		},'json');
		
	}
	
	
});
function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}
function kFormatter(num) {
	// return num;
    return Math.abs(num) > 999 ? Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num)
}

</script>

<link rel="stylesheet" href="../0/qa.css?1.44">
<link rel="stylesheet" type="text/css" href="../0/simditor.min.css" />
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
		<div class="sidebar-box ">
				

<style>	
.responsive_ad1 { display:none; }
@media(min-width: 800px) { .responsive_ad1 {  display:block;margin:0 auto;} }
</style>
<div id="ad-336280" >

<script async src=""
     crossorigin="anonymous"></script>
<!-- 移动版 自动调整 -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-5751451760833794"
     data-ad-slot="1691338467"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
		</div>
				</div>
		
	</div>
</div>
	

<!-- 右边栏 -->
<div class="fivecol last right-column">

<style>
.sidebar-tree .double-li {
    width:300px;
}
.sidebar-tree .double-li li {
    width: 44%;
    line-height: 1.5em;
    border-bottom: 1px solid #ccc;
    float: left;
    display: inline;
}
</style>

    
        <div class="sidebar-box re-box re-box-large">
        <div class="sidebar-box recommend-here" style="margin: 0 auto;">
            <a href="javascript:void(0);" style="font-size: 16px; color:#64854c;font-weight:bold;"> <i class="fa fa-list" aria-hidden="true"></i> 分类导航</a>
        </div>
    <div class="sidebar-box sidebar-cate">
        
        <div class="sidebar-tree" >
            <ul><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> HTML / CSS</a><ul class="double-li"><li><a title="HTML 教程" href="../html/html-tutorial.html">HTML 教程</a></li><li><a title="HTML5 教程" href="../html/html5-intro.html">HTML5 教程</a></li><li><a title="CSS 教程" href="../css/css-tutorial.html">CSS 教程</a></li><li><a title="CSS3 教程" href="../css3/css3-tutorial.html">CSS3 教程</a></li><li><a title="Bootstrap3 教程" href="../bootstrap/bootstrap-tutorial.html">Bootstrap3 教程</a></li><li><a title="Bootstrap4 教程" href="../bootstrap4/bootstrap4-tutorial.html">Bootstrap4 教程</a></li><li><a title="Bootstrap5 教程" href="../bootstrap5/bootstrap5-tutorial.html">Bootstrap5 教程</a></li><li><a title="Font Awesome 教程" href="../font-awesome/fontawesome-tutorial.html">Font Awesome 教程</a></li><li><a title="Foundation 教程" href="../foundation/foundation-tutorial.html">Foundation 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> JavaScript</a><ul class="double-li"><li><a title="JavaScript 教程" href="../js/js-tutorial.html">JavaScript 教程</a></li><li><a title="HTML DOM 教程" href="../htmldom/htmldom-tutorial.html">HTML DOM 教程</a></li><li><a title="jQuery 教程" href="../jquery/jquery-tutorial.html">jQuery 教程</a></li><li><a title="AngularJS 教程" href="../angularjs/angularjs-tutorial.html">AngularJS 教程</a></li><li><a title="AngularJS2 教程" href="../angularjs2/angularjs2-tutorial.html">AngularJS2 教程</a></li><li><a title="Vue.js 教程" href="../vue2/vue-tutorial.html">Vue.js 教程</a></li><li><a title="Vue3 教程" href="../vue3/vue3-tutorial.html">Vue3 教程</a></li><li><a title="React 教程" href="../react/react-tutorial.html">React 教程</a></li><li><a title="TypeScript 教程" href="../typescript/ts-tutorial.html">TypeScript 教程</a></li><li><a title="jQuery UI 教程" href="../jqueryui/jqueryui-tutorial.html">jQuery UI 教程</a></li><li><a title="jQuery EasyUI 教程" href="../jeasyui/jqueryeasyui-tutorial.html">jQuery EasyUI 教程</a></li><li><a title="Node.js 教程" href="../nodejs/nodejs-tutorial.html">Node.js 教程</a></li><li><a title="AJAX 教程" href="../ajax/ajax-tutorial.html">AJAX 教程</a></li><li><a title="JSON 教程" href="../json/json-tutorial.html">JSON 教程</a></li><li><a title="Echarts 教程" href="../echarts/echarts-tutorial.html">Echarts 教程</a></li><li><a title="Chart.js 教程" href="../chartjs/chartjs-tutorial.html">Chart.js 教程</a></li><li><a title="Highcharts 教程" href="../highcharts/highcharts-tutorial.html">Highcharts 教程</a></li><li><a title="Google 地图 教程" href="../googleapi/google-maps-basic.html">Google 地图 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 服务端</a><ul class="double-li"><li><a title="Python 教程" href="../python3/python3-tutorial.html">Python 教程</a></li><li><a title="Python2.x 教程" href="../python/python-tutorial.html">Python2.x 教程</a></li><li><a title="Linux 教程" href="../linux/linux-tutorial.html">Linux 教程</a></li><li><a title="Docker 教程" href="../docker/docker-tutorial.html">Docker 教程</a></li><li><a title="Ruby 教程" href="../ruby/ruby-tutorial.html">Ruby 教程</a></li><li><a title="Java 教程" href="../java/java-tutorial.html">Java 教程</a></li><li><a title="C 教程" href="../c/c-tutorial.html">C 教程</a></li><li><a title="C++ 教程" href="../cplusplus/cpp-tutorial.html">C++ 教程</a></li><li><a title="Perl 教程" href="../perl/perl-tutorial.html">Perl 教程</a></li><li><a title="Servlet 教程" href="../servlet/servlet-tutorial.html">Servlet 教程</a></li><li><a title="JSP 教程" href="../jsp/jsp-tutorial.html">JSP 教程</a></li><li><a title="Lua 教程" href="../lua/lua-tutorial.html">Lua 教程</a></li><li><a title="Rust 教程" href="../rust/rust-tutorial.html">Rust 教程</a></li><li><a title="Scala 教程" href="../scala/scala-tutorial.html">Scala 教程</a></li><li><a title="Go 教程" href="../go/go-tutorial.html">Go 教程</a></li><li><a title="PHP 教程" href="../php/php-tutorial.html">PHP 教程</a></li><li><a title="数据结构与算法" href="../data-structures/data-structures-tutorial.html">数据结构与算法</a></li><li><a title="Django 教程" href="../django/django-tutorial.html">Django 教程</a></li><li><a title="Zookeeper 教程" href="../w3cnote/zookeeper-tutorial.html">Zookeeper 教程</a></li><li><a title="设计模式" href="../design-pattern/design-pattern-tutorial.html">设计模式</a></li><li><a title="正则表达式" href="../regexp/regexp-tutorial.html">正则表达式</a></li><li><a title="Maven 教程" href="../maven/maven-tutorial.html">Maven 教程</a></li><li><a title="Verilog 教程" href="../w3cnote/verilog-tutorial.html">Verilog 教程</a></li><li><a title="ASP 教程" href="../asp/asp-tutorial.html">ASP 教程</a></li><li><a title="AppML 教程" href="../appml/appml-tutorial.html">AppML 教程</a></li><li><a title="VBScript 教程" href="../vbscript/vbscript-tutorial.html">VBScript 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 数据库</a><ul class="double-li"><li><a title="SQL 教程" href="../sql/sql-tutorial.html">SQL 教程</a></li><li><a title="MySQL 教程" href="../mysql/mysql-tutorial.html">MySQL 教程</a></li><li><a title="PostgreSQL 教程" href="../postgresql/postgresql-tutorial.html">PostgreSQL 教程</a></li><li><a title="SQLite 教程" href="../sqlite/sqlite-tutorial.html">SQLite 教程</a></li><li><a title="MongoDB 教程" href="../mongodb/mongodb-tutorial.html">MongoDB 教程</a></li><li><a title="Redis 教程" href="../redis/redis-tutorial.html">Redis 教程</a></li><li><a title="Memcached 教程" href="../Memcached/Memcached-tutorial.html">Memcached 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 数据分析</a><ul class="double-li"><li><a title="Python 教程" href="../python3/python3-tutorial.html">Python 教程</a></li><li><a title="NumPy 教程" href="../numpy/numpy-tutorial.html">NumPy 教程</a></li><li><a title="Pandas 教程" href="../pandas/pandas-tutorial.html">Pandas 教程</a></li><li><a title="Matplotlib 教程" href="../matplotlib/matplotlib-tutorial.html">Matplotlib 教程</a></li><li><a title="Scipy 教程" href="../scipy/scipy-tutorial.html">Scipy 教程</a></li><li><a title="R 教程" href="../r/r-tutorial.html">R 教程</a></li><li><a title="Julia 教程" href="../julia/julia-tutorial.html">Julia 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 移动端</a><ul class="double-li"><li><a title="Android 教程" href="../w3cnote/android-tutorial-intro.html">Android 教程</a></li><li><a title="Swift 教程" href="../swift/swift-tutorial.html">Swift 教程</a></li><li><a title="jQuery Mobile 教程" href="../jquerymobile/jquerymobile-tutorial.html">jQuery Mobile 教程</a></li><li><a title="ionic 教程" href="../ionic/ionic-tutorial.html">ionic 教程</a></li><li><a title="Kotlin 教程" href="../kotlin/kotlin-tutorial.html">Kotlin 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> XML 教程</a><ul class="double-li"><li><a title="XML 教程" href="../xml/xml-tutorial.html">XML 教程</a></li><li><a title="DTD 教程" href="../dtd/dtd-tutorial.html">DTD 教程</a></li><li><a title="XML DOM 教程" href="../dom/dom-tutorial.html">XML DOM 教程</a></li><li><a title="XSLT 教程" href="../xsl/xsl-tutorial.html">XSLT 教程</a></li><li><a title="XPath 教程" href="../xpath/xpath-tutorial.html">XPath 教程</a></li><li><a title="XQuery 教程" href="../xquery/xquery-tutorial.html">XQuery 教程</a></li><li><a title="XLink 教程" href="../xlink/xlink-tutorial.html">XLink 教程</a></li><li><a title="XPointer 教程" href="../xlink/xlink-tutorial.html">XPointer 教程</a></li><li><a title="XML Schema 教程" href="../schema/schema-tutorial.html">XML Schema 教程</a></li><li><a title="XSL-FO 教程" href="../xslfo/xslfo-tutorial.html">XSL-FO 教程</a></li><li><a title="SVG 教程" href="../svg/svg-tutorial.html">SVG 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> ASP.NET</a><ul class="double-li"><li><a title="ASP.NET 教程" href="../aspnet/aspnet-tutorial.html">ASP.NET 教程</a></li><li><a title="C# 教程" href="../csharp/csharp-tutorial.html">C# 教程</a></li><li><a title="Web Pages 教程" href="../aspnet/webpages-intro.html">Web Pages 教程</a></li><li><a title="Razor 教程" href="../aspnet/razor-intro.html">Razor 教程</a></li><li><a title="MVC 教程" href="../aspnet/mvc-intro.html">MVC 教程</a></li><li><a title="Web Forms 教程" href="../aspnet/aspnet-intro.html">Web Forms 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> Web Service</a><ul class="double-li"><li><a title="Web Service 教程" href="../webservices/webservices-tutorial.html">Web Service 教程</a></li><li><a title="WSDL 教程" href="../wsdl/wsdl-tutorial.html">WSDL 教程</a></li><li><a title="SOAP 教程" href="../soap/soap-tutorial.html">SOAP 教程</a></li><li><a title="RSS 教程" href="../rss/rss-tutorial.html">RSS 教程</a></li><li><a title="RDF 教程" href="../rdf/rdf-tutorial.html">RDF 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 开发工具</a><ul class="double-li"><li><a title="Eclipse 教程" href="../eclipse/eclipse-tutorial.html">Eclipse 教程</a></li><li><a title="Git 教程" href="../git/git-tutorial.html">Git 教程</a></li><li><a title="Svn 教程" href="../svn/svn-tutorial.html">Svn 教程</a></li><li><a title="Markdown 教程" href="../markdown/md-tutorial.html">Markdown 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 网站建设</a><ul class="double-li"><li><a title="HTTP 教程" href="../http/http-tutorial.html">HTTP 教程</a></li><li><a title="网站建设指南" href="../web/web-buildingprimer.html">网站建设指南</a></li><li><a title="浏览器信息" href="../browsers/browser-information.html">浏览器信息</a></li><li><a title="网站主机教程" href="../hosting/hosting-tutorial.html">网站主机教程</a></li><li><a title="TCP/IP 教程" href="../tcpip/tcpip-tutorial.html">TCP/IP 教程</a></li><li><a title="W3C 教程" href="../w3c/w3c-tutorial.html">W3C 教程</a></li><li><a title="网站品质" href="../quality/quality-tutorial.html">网站品质</a></li></ul></li></ul>            </div>
    
    </div>
    </div>
    <br>
    
    <div class="sidebar-box re-box re-box-large">
        <div class="sidebar-box recommend-here">
            <a href="javascript:void(0);">Advertisement</a>
        </div>
        <div class="re-600160" id="sidebar-right-re">
                <script async src=""></script>
        <!-- 侧栏1 -->
        <ins class="adsbygoogle"
             style="display:inline-block;width:160px;height:600px"
             data-ad-client="ca-pub-5751451760833794"
             data-ad-slot="4106274865"></ins>
        <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
                </div>
    </div>
</div></div>

</div>

<script>
var aid = 5138;
function coll() {
	$.post( '/wp-content/themes/runoob/option/user/userinfo.php', {aid:aid, action:"collarticle", opt:'add'},function( data ) {
		if(data.error==0) {
			$("#content").find("h1:first").find("a").attr("href","javascript:void(0);");
			$("#content").find("h1:first").find("img").attr("src","http://www.runoob.com/wp-content/themes/runoob/assets/img/coll2.png").css({width:32+"px",height:32+"px"});
		}
		alert(data.msg);
	},'json');
}
</script>


<!-- 反馈对话框开始 -->
<script src=""></script>
<link rel="stylesheet" href="../0/feedback.css?1.0" />
<script type="text/javascript">
$.feedback({
    ajaxURL: '/feedback/runoob_feedback.php',
	html2canvasURL: '/wp-content/themes/runoob/assets/feedback/stable/2.0/html2canvas.js',
	onClose: function () {
         window.location.reload();
    }
});
</script>
<!-- 反馈对话框结束 -->
<button class="feedback-btn feedback-btn-gray">反馈/建议</button>
<!-- 底部 -->
<div id="footer" class="mar-t50">
   <div class="runoob-block">
    <div class="runoob cf">
     <dl>
      <dt>
       在线实例
      </dt>
      <dd>
       &middot;<a target="_blank" href="../html/html-examples.html">HTML 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../css/css-examples.html">CSS 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../js/js-examples.html">JavaScript 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../ajx/ajax-examples.html">Ajax 实例</a>
      </dd>
       <dd>
       &middot;<a target="_blank" href="../jquery/jquery-examples.html">jQuery 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../xml/xml-examples.html">XML 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../java/java-examples.html">Java 实例</a>
      </dd>
     
     </dl>
     <dl>
      <dt>
      字符集&工具
      </dt>
      <dd>
       &middot; <a target="_blank" href="../charsets/html-charsets.html">HTML 字符集设置</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="../tags/html-ascii.html">HTML ASCII 字符集</a>
      </dd>
     <dd>
       &middot; <a target="_blank" href="https://c.runoob.com/front-end/6939/">JS 混淆/加密</a>
      </dd> 
      <dd>
       &middot; <a target="_blank" href="https://c.runoob.com/front-end/6232/">PNG/JPEG 图片压缩</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="../tags/html-colorpicker.html">HTML 拾色器</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="..//c.runoob.com/front-end/53">JSON 格式化工具</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="..//c.runoob.com/front-end/6680/">随机数生成器</a>
      </dd>
     </dl>
     <dl>
      <dt>
       最新更新
      </dt>
                   <dd>
       &middot;
      <a href="../matplotlib/matplotlib-imread.html" title="Matplotlib imread() 方法">Matplotlib imre...</a>
      </dd>
              <dd>
       &middot;
      <a href="../matplotlib/matplotlib-imsave.html" title="Matplotlib imsave() 方法">Matplotlib imsa...</a>
      </dd>
              <dd>
       &middot;
      <a href="../matplotlib/matplotlib-imshow.html" title="Matplotlib imshow() 方法">Matplotlib imsh...</a>
      </dd>
              <dd>
       &middot;
      <a href="../matplotlib/matplotlib-hist.html" title="Matplotlib 直方图">Matplotlib 直方图</a>
      </dd>
              <dd>
       &middot;
      <a href="../python3/python-func-object.html" title="Python object() 函数">Python object()...</a>
      </dd>
              <dd>
       &middot;
      <a href="../python3/python-ai-draw.html" title="Python AI 绘画">Python AI 绘画</a>
      </dd>
              <dd>
       &middot;
      <a href="../w3cnote/cursor-editor.html" title="神辅助 Cursor 编辑器，加入 GPT-4 让编码更轻松！">神辅助 Cursor ...</a>
      </dd>
             </dl>
     <dl>
      <dt>
       站点信息
      </dt>
      <dd>
       &middot;
       <a target="_blank" href="mailto:admin@runoob.com" rel="external nofollow">意见反馈</a>
       </dd>
      <dd>
       &middot;
      <a target="_blank" href="../disclaimer">免责声明</a>
       </dd>
      <dd>
       &middot;
       <a target="_blank" href="../aboutus">关于我们</a>
       </dd>
      <dd>
       &middot;
      <a target="_blank" href="../archives">文章归档</a>
      </dd>
    
     </dl>
    
     <div class="search-share">
      <div class="app-download">
        <div>
         <strong>关注微信</strong>
        </div>
      </div>
      <div class="share">
      <img width="128" height="128" src="/wp-content/themes/runoob/assets/images/qrcode.png" />
       </div>
     </div>
     
    </div>
   </div>
   <div class="w-1000 copyright">
     Copyright &copy; 2013-2023    <strong><a href="../" target="_blank">菜鸟教程</a></strong>&nbsp;
    <strong><a href="../" target="_blank">runoob.com</a></strong> All Rights Reserved. 备案号：<a target="_blank" rel="nofollow" href="https://beian.miit.gov.cn/">闽ICP备15012807号-1</a>
   </div>
  </div>
  <div class="fixed-btn">
    <a class="go-top" href="javascript:void(0)" title="返回顶部"> <i class="fa fa-angle-up"></i></a>
    <a class="qrcode"  href="javascript:void(0)" title="关注我们"><i class="fa fa-qrcode"></i></a>
    <a class="writer" style="display:none" href="javascript:void(0)"   title="标记/收藏"><i class="fa fa-star" aria-hidden="true"></i></a>
    <!-- qrcode modal -->
    <div id="bottom-qrcode" class="modal panel-modal hide fade in">
      <h4>微信关注</h4>
      <div class="panel-body"><img alt="微信关注" width="128" height="128" src="/wp-content/themes/runoob/assets/images/qrcode.png"></div> 
    </div>
  </div>

 <div style="display:none;">
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-84264393-2"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-84264393-2');
</script>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?3eec0b7da6548cf07db3bc477ea905ee";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

</div>
<script>
window.jsui={
    www: 'https://www.runoob.com',
    uri: 'https://www.runoob.com/wp-content/themes/runoob'
};
</script>

<script src=""></script>
<script src=""></script>

</body>
</html>